package com.kkb.controller;

import com.github.pagehelper.PageInfo;
import com.kkb.pojo.MedicinePeople;
import com.kkb.pojo.PricePeople;
import com.kkb.service.MedicinePeopleService;
import com.kkb.vo.MedicinePeopleInsertVO;
import com.kkb.vo.MedicinePeopleQueryVO;
import com.kkb.vo.PricePeopleQueryVO;
import com.kkb.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping("medicinePeople")
public class MedicinePeopleController {

    @Resource
    MedicinePeopleService service;

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultVO add(MedicinePeople medicinePeople) {
        int result = service.add(medicinePeople);
        return result == 1 ? new ResultVO("新增成功!") : new ResultVO(500, "新增失败!");
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVO queryAll(int index, int size, MedicinePeopleQueryVO vo) {
        PageInfo pageInfo = service.queryAll(index, size, vo);
        return new ResultVO(pageInfo);
    }

    @RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
    public ResultVO queryByPatientId(@PathVariable("id") int id) {
        List list = service.queryByPatientId(id);
        if (list == null) {
            return new ResultVO(500, "服务器异常!");
        } else {
            return new ResultVO(list);
        }
    }

    @RequestMapping(value = "addByList", method = RequestMethod.POST)
    public ResultVO insertByList(MedicinePeopleInsertVO vo) {
        int result = service.addByList(vo);
        return result == vo.getIds().size() ? new ResultVO("成功") : new ResultVO(500, vo.getIds().size() - result + "条数据插入失败");
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @RequestMapping(value = "dispense", method = RequestMethod.PUT)
    public ResultVO dispense(int id, int number) {
        MedicinePeople medicinePeople = new MedicinePeople();
        medicinePeople.setId(id);
        MedicinePeople people = service.queryById(id);
        if (people.getDiNumber() + number > people.getDrNumber()) {
            return new ResultVO<>(405, "发药失败，剩余量不足");
        } else {
            medicinePeople.setDiNumber(people.getDiNumber() + number);
            int result = service.update(medicinePeople);
            return result == 1 ? new ResultVO("成功") : new ResultVO(500, "失败");
        }
    }
}
